<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <!-- <el-form-item label="变电站id" prop="substationId">
          <el-input
            v-model="queryParams.substationId"
            placeholder="请输入变电站id"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="设备编号" prop="deviceNo">
          <el-input
            v-model="queryParams.deviceNo"
            placeholder="请输入设备编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <el-form-item label="地区" prop="id">
          <el-select v-model="queryParams.id" clearable placeholder="请选择地区">
            <el-option
              v-for="item in areaOptions"
              :key="item.id"
              :label="item.areaName"
              :value="item.id">
            </el-option>
          </el-select>
          <!-- <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter.native="handleQuery"
          /> -->
        </el-form-item>
        <!-- <el-form-item label="开关编号" prop="switchNo">
          <el-input
            v-model="queryParams.switchNo"
            placeholder="请输入开关编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="调度名称" prop="scheduleName">
          <el-input
            v-model="queryParams.scheduleName"
            placeholder="请输入调度名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="装置版本号" prop="deviceVersion">
          <el-input
            v-model="queryParams.deviceVersion"
            placeholder="请输入装置版本号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="校验码" prop="checkCode">
          <el-input
            v-model="queryParams.checkCode"
            placeholder="请输入校验码"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="电压等级" prop="voltageLevel">
          <el-input
            v-model="queryParams.voltageLevel"
            placeholder="请输入电压等级"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <!-- <el-form-item label="CT变比" prop="ctTransformationRatio">
          <el-input
            v-model="queryParams.ctTransformationRatio"
            placeholder="请输入CT变比"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="PT变比" prop="ptTransformationRatio">
          <el-input
            v-model="queryParams.ptTransformationRatio"
            placeholder="请输入PT变比"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['substation:substationDevice:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['substation:substationDevice:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['substation:substationDevice:remove']"
          >删除</el-button>
        </el-col>
        <el-button 
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:user:import']"
        >导入</el-button>
        <!-- <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['substation:substationDevice:export']"
          >导出</el-button>
        </el-col> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="substationDeviceList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备编号" align="center" prop="id"  width="200"/>
        <el-table-column label="所属区域" align="center" prop="areaName"  width="230"/>
        <el-table-column label="变电站名称" align="center" prop="substationName" width="285"/>
        <el-table-column label="变电站类型" align="center" prop="typeName" width="285"/>
        <el-table-column label="所属班组长" align="center" prop="leaderName" width="285"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="detailList(scope.row)"
             >参数详情</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['substation:substationDevice:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['substation:substationDevice:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div class="toNew" @click = "toNew">跳转</div>
  
      <!-- 添加或修改变电站设备信息对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <!-- <el-form-item label="变电站id" prop="substationId">
            <el-input v-model="form.substationId" placeholder="请输入变电站id" />
          </el-form-item> -->
          <el-form-item label="所属变电站" >
            <el-select v-model="form.substationId" clearable placeholder="请选择所属变电站" style="width:100%">
              <el-option
                v-for="item in typeOptions"
                :key="item.substationId"
                :label="item.substationName"
                :value="item.substationId">
              </el-option>
            </el-select>
            <!-- <el-input v-model="form.substationName" placeholder="请输入所属变电站" /> -->
          </el-form-item>
          <el-form-item label="设备编号" prop="id">
            <el-input v-model="form.id" placeholder="请输入设备编号" :disabled="true"/>
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
          </el-form-item>
          <el-form-item label="开关编号" prop="switchNo">
            <el-input v-model="form.switchNo" placeholder="请输入开关编号" />
          </el-form-item>
          <el-form-item label="调度名称" prop="scheduleName">
            <el-input v-model="form.scheduleName" placeholder="请输入调度名称" />
          </el-form-item>
          <el-form-item label="装置版本号" prop="deviceVersion">
            <el-input v-model="form.deviceVersion" placeholder="请输入装置版本号" />
          </el-form-item>
          <el-form-item label="校验码" prop="checkCode">
            <el-input v-model="form.checkCode" placeholder="请输入校验码" />
          </el-form-item>
          <!-- <el-form-item label="电压等级" prop="voltageLevel">
            <el-input v-model="form.voltageLevel" placeholder="请输入电压等级" />
          </el-form-item> -->
          <el-form-item label="CT变比" prop="ctTransformationRatio">
            <el-input v-model="form.ctTransformationRatio" placeholder="请输入CT变比" />
          </el-form-item>
          <el-form-item label="PT变比" prop="ptTransformationRatio">
            <el-input v-model="form.ptTransformationRatio" placeholder="请输入PT变比" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
  
        
      <!-- 设备参数详情列表 -->
      <el-dialog :title="title" :visible.sync="openDetail" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="设备保护型号">
            <el-select v-model="form.protectDeviceModel" clearable placeholder="请选择设备保护型号">
              <el-option
                v-for="item in protectDeviceOptions"
                :key="item.id"
                :label="item.protectDeviceModel"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="保护装置类型" prop="protectDeviceType" v-if="form.protectDeviceModel">
            <el-input v-model="form.protectDeviceType" placeholder="请输入保护装置类型" />
          </el-form-item>
          <el-form-item label="原理图" prop="principleImgUrl" v-if="form.protectDeviceModel">
            <img width="100%" :src="baseUrl + form.principleImgUrl" alt="" style="width: 130px;height: 130px;margin: 10px;">
            <!-- <el-input v-model="form.principleImgUrl" placeholder="请输入设备名称" /> -->
          </el-form-item>
          <el-form-item label="厂家名称" prop="manufacturer" v-if="form.protectDeviceModel">
            <el-input v-model="form.manufacturer" placeholder="请输入厂家名称" />
          </el-form-item>
          <el-form-item label="请选择版本" v-if="form.protectDeviceModel">
            <template>
              <el-radio-group v-model="value">
                <el-radio v-for="item in copyList" 
                  :label="item.value"
                  :key="item.value">{{item.label}}</el-radio>
              </el-radio-group>
            </template>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" v-if="form.protectDeviceModel">
          <el-button type="primary" @click="chooseVersion" >确 定</el-button>
          <el-button @click="openDetail = false"  >取 消</el-button>
        </div>
      </el-dialog>
  
          <!-- 设备参数详情 -->
          <el-dialog :title="title" :visible.sync="openList" width="900px" append-to-body>
            <el-button
            size="medium"
            type="text"
            icon="el-icon-search"
             >参数附件</el-button>
            <el-table :data="tableData" height="250" border style="width: 100%" >
              <el-table-column prop="serialNo" label="序号" width="180" align="center"></el-table-column>
              <el-table-column prop="name" label="名称" width="180" align="center"></el-table-column>
              <el-table-column label="定值" align="center" >
                <template slot-scope="scope" >
                  <el-popover
                    v-if="scope.row.different == 2"
                    placement="right"
                    width="500"
                    trigger="click"
                    @show="firstShow(scope.row, scope.$index)"
                    >
                    <el-table :data="gridData">
                      <el-table-column property="fileDate" label="日期" align="center" width="150"></el-table-column>
                      <el-table-column property="constantValue" label="数值" align="center" width="100"></el-table-column>
                      <el-table-column property="fileNo" label="字号" align="center" width="250"></el-table-column>
                    </el-table>
                    <div slot="reference" :style="{
                      'color': (scope.row.different == 2) ? 'red' : 'black'
                      }">{{scope.row.constantValue}}</div>
                  </el-popover>
                  <div slot="reference" v-else>{{scope.row.constantValue}}</div>
              </template>
              </el-table-column>
  
              <el-table-column prop="remarks[0].nickName" label="备注" align="center"></el-table-column>
            </el-table>
          </el-dialog>
  
        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <!-- <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div> -->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listSubstationDevice, getSubstationDevice, delSubstationDevice, addSubstationDevice, updateSubstationDevice,getProtectDeviceList } from "@/api/substation/substationDevice";
  import { getProtectDevice} from "@/api/substation/protectDevice.js";
  import { getVersionList } from "@/api/substation/version.js";
  import { listParameterDetails,getHistory } from "@/api/substation/parameterDetails.js";
  import { listSubstation } from "@/api/substation/substation.js";
  import { listArea } from "@/api/substation/area.js";
  import { getToken } from "@/utils/auth";
  
  export default {
    name: "SubstationDevice",
    data() {
      return {
        value:'',
        id:'',
        baseUrl: process.env.VUE_APP_BASE_API,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 变电站设备信息表格数据
        substationDeviceList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          id:null,
          pageNum: 1,
          pageSize: 10,
          substationId: null,
          deviceNo: null,
          deviceName: null,
          switchNo: null,
          scheduleName: null,
          deviceVersion: null,
          checkCode: null,
          voltageLevel: null,
          ctTransformationRatio: null,
          ptTransformationRatio: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          // updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/substation/substationDevice/importData"
        },
        openDetail:false,
        version:false,
        radio: '1',
        openList:false,
        tableData: [],
        typeOptions:[],
        protectDeviceOptions:[],
        protectDeviceId:'',
        copyList:[],
        gridData:[],
        areaOptions:[]
      };
    },
    created() {
      this.getList();
      this.getAreaOptions()
    },
    mounted() {
      const unWatch = this.$watch("form.protectDeviceModel", (newVal, oldVal) => {
        // console.log(newVal,'newValue',newVal && !oldVal)
        if(newVal && !oldVal){
          this.protectDeviceId = newVal
            getProtectDevice(newVal).then(response => {
              this.form = response.data;
            });
          }else{
            getVersionList({
              protectDeviceId:this.protectDeviceId,
              deviceId:this.id
            }).then(response => {
              this.copyList = response.data
            });
          }
        // unWatch(); // 取消监听
      });
    },
    methods: {
      getAreaOptions(){
        this.loading = true;
        listArea(999).then(response => {
          this.areaOptions = response.rows.map(item => {
            return {
              id: item.id,
              areaName: item.areaName
            }
          })
          this.loading = false;
          console.log(this.areaOptions,'data')
        }); 
      },
      toNew(){
        this.$router.push("/substation/newDetails");
      },
      firstShow(e,a){
        // console.log(e,'wwwwwwwwww',a)
        getHistory({
          deviceProtectVersionId: e.deviceProtectVersionId,
          serialNo:e.serialNo
        }).then(response => {
          this.gridData = response.data
          // console.log(response,'data')
        }); 
      },
      // 查询所有变电站类型
      // getAlltype(){
      //   this.loading = true;
      //   getAllTypeList().then(response => {
      //     this.typeOptions = response.data
      //     this.loading = false;
      //   });
      // },
      // 选择版本
      chooseVersion(e){
        listParameterDetails({
          deviceProtectVersionId: this.value
        }).then(response => {
          console.log(response.rows,'data')
          this.tableData = response.rows
          this.openDetail = false
          this.openList = true
          this.title = "设备参数";
        }); 
      },
       // 提交上传文件
       submitFileForm() {
        this.$refs.upload.submit();
      },
       // 文件上传成功处理
       handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      importTemplate() {
        this.download('system/user/importTemplate', {
        }, `user_template_${new Date().getTime()}.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },
      /** 查询保护装置信息列表 */
      // getList() {
      //   this.loading = true;
      //   listProtectDevice(this.queryParams).then(response => {
      //     this.protectDeviceList = response.rows;
      //     this.total = response.total;
      //     this.loading = false;
      //   });
      // },
      
  
      /** 查询变电站设备信息列表 */
      getList() {
        this.loading = true;
        listSubstation(this.queryParams).then(response => {
          this.substationDeviceList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          substationId: null,
          deviceNo: null,
          deviceName: null,
          switchNo: null,
          scheduleName: null,
          deviceVersion: null,
          checkCode: null,
          voltageLevel: null,
          ctTransformationRatio: null,
          ptTransformationRatio: null,
          createTime: null,
          createBy: null,
          updateTime: null,
          updateBy: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.queryParams.id = '';
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加变电站设备信息";
      },
      /** 参数详情操作 */
      detailList(row) {
        this.reset();
        const id = row.id || this.ids
        this.id = id
        this.loading = true;
        /** 查询变电站设备保护装置列表 */
        getProtectDeviceList({id:id}).then(response => {
          this.form = {};
          this.protectDeviceOptions = response.data.map(item => {
            return {
              id:item.id,
              protectDeviceModel:item.protectDeviceModel
            }
          })
          this.title = "设备参数列表";
          this.openDetail = true;
          this.loading = false;
        });
        
        // const id = row.id || this.ids
       
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        this.queryParams.pageSize = 999
        this.loading = true;
        
        getSubstationDevice(id).then(response => {
          this.form = response.data;
          console.log(this.form,'this.form')
          this.open = true;
          this.title = "修改变电站设备信息";
        });
        // listSubstation(this.queryParams).then(response => {
        //   // this.form.id = ''
        //   this.typeOptions = response.rows.map(item => {
        //     return {
        //       substationId:item.id,
        //       substationName:item.substationName
        //     }
        //   });
        //   this.loading = false;
        // });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          console.log(this.form,'修改')
          if (valid) {
            if (this.form.id != null) {
              updateSubstationDevice(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addSubstationDevice(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除变电站设备信息编号为"' + ids + '"的数据项？').then(function() {
          return delSubstationDevice(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('substation/substationDevice/export', {
          ...this.queryParams
        }, `substationDevice_${new Date().getTime()}.xlsx`)
      }
    }
  };
  </script>
  